import { OrderModel } from '../../../../models/order'

import { PayModel } from '../../../../models/pay.js'
import { encryptString } from '../../../../utils/index.js'
import { AppModel } from '../../../../models/app.js'
const appModel = new AppModel()

var pingpp = require('../../../../utils/pingpp.js')

const ModelPay = new PayModel()

const orderDetailModel = new OrderModel()
const App = getApp()

Page({
  /**
     * 页面的初始数据
     */
  data: {
    orderDetails: {},
    orderBtnArr: [
      {},
      {
        btnArr: [{ name: '撤销订单', class: 'undo' }, { name: '支付', class: 'pay' }]
      },
      {},
      {},
      { btnArr: [{ name: '确认收货', class: 'confirm' }] },
      {},
      {}
    ],
    orderid: '',
    channel: 8, //支付渠道：1支付宝App支付，2支付宝扫码支付，3微信App支付，4微信公众号支付，5微信扫码支付，6余额支付，7智荟金桥，8微信小程序支付
    statusBarHeight: App.globalData.statusBarHeight,
    isTabbar:false
  },

  //获取订单详情
  getOrderDetail: function() {
    const self = this
    const params = {
      orderId: self.data.orderid
    }

    orderDetailModel
      .getOrderDetail(params)
      .then(res => {
        this.setData({
          orderDetails: res.data.orderDetails
        })
        wx.stopPullDownRefresh()
      })
      .catch()
  },

  //撤销订单
  undo: function(e) {
    const self = this
    const params = {
      orderId: e.currentTarget.dataset.id
    }
    orderDetailModel
      .revokeOrder(params)
      .then(res => {
        // self.getOrderList();
        App.WxService.showToast({ title: '撤销成功', icon: 'none' })
        wx.navigateTo({
          url: '/pages/account/order/list/index'
        })
      })
      .catch()
  },

  //支付订单
  pay: function(e) {
    var info = this.data.orderDetails
    const self = this
    const orderIds = []
    //订单加密
    orderIds.push(encryptString(info.id, 1))

    const params = {
      orderIds: orderIds,
      amount: (info.orderAmount / 100).toFixed(2),
      channel: self.data.channel,
      open_id: App.globalData.userInfo.openId
    }

    ModelPay.pay(params)
      .then(res => {
        pingpp.createPayment(res.data.order, function(result, err) {
          if (result == 'success') {
            // 只有微信公众号 (wx_pub)、微信小程序（wx_lite）、QQ 公众号 (qpay_pub)支付成功的结果会在这里返回，其他的支付结果都会跳转到 extra 中对应的 URL
            // 查询支付结果
            const params = { pid: res.data.pid }
            setTimeout(function() {
              return ModelPay.payResult(params).then(res => {
                if (res.status == 200) {
                  App.WxService.showToast({
                    title: '支付成功',
                    icon: 'none'
                  })
                  App.WxService.redirectTo(
                    '/packCart/pages/payOrder/success/index?pid=' + res.data.payCode
                  )
                
                }
              })
            }, 1000)
          } else if (result == 'fail') {
            App.WxService.showToast({
              title: '支付失败',
              icon: 'none'
            })
            self.getOrderDetail();
            // Ping++ 对象 object 不正确或者微信公众号/微信小程序/QQ公众号支付失败时会在此处返回
          } else if (result == 'cancel') {
            // 微信公众号、微信小程序、QQ 公众号支付取消支付
            App.WxService.showToast({
              title: '取消支付',
              icon: 'none'
            })
            setTimeout(function() {
              self.onLoad()
            }, 1000)
          }
        })
      })
   
      .catch(err => {
        console.log(err)
      })
  },

  //确认收货
  confirm: function(e) {
    wx.showModal({
      title: '提示',
      content: '是否确认收货？',
      success: function(res) {
        if (res.confirm) {
          //确认收货，发送收货请求
          const params = {
            orderId: e.currentTarget.dataset.id
          }
          orderDetailModel
            .confirmGoods(params)
            .then(res => {
              if (res.info == 'success') {
                App.WxService.showToast({ title: '确认收货成功', icon: 'none' })
                wx.navigateTo({
                  url:
                    '/pages/account/order/confirm/index?orderId=' +
                    params.orderId +
                    '&evaluateGold=' +
                    res.data.evaluateGold
                })
              }
            })
            .catch()
        } else if (res.cancel) {
          console.log('取消确认收货')
        }
      }
    })
  },

  //查看物流信息
  express: function(e) {
    const expressName = e.currentTarget.dataset.expressname
    const expressCode = e.currentTarget.dataset.expresscode
    wx.setClipboardData({
      data: expressCode,
      success(res) {
        App.WxService.showToast({ title: '单号复制成功', icon: 'none' })
      }
    })
    // wx.navigateTo({
    //   url: '/pages/account/order/express/index?expressName=' + expressName + '&expressCode=' + expressCode,
    // })
  },

  /**
     * 生命周期函数--监听页面加载
     */
  onLoad: function(options) {
    this.setData({
      orderid: options.orderid
    })
    this.getOrderDetail()
  },

  /**
     * 生命周期函数--监听页面初次渲染完成
     */
  onReady: function() {},

  /**
     * 生命周期函数--监听页面显示
     */
  onShow: function() {
    this.getOrderDetail()
  },

  /**
     * 生命周期函数--监听页面隐藏
     */
  onHide: function() {},

  /**
     * 生命周期函数--监听页面卸载
     */
  onUnload: function() {},

  /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
  onPullDownRefresh: function() {
    this.getOrderDetail()
  },

  /**
     * 页面上拉触底事件的处理函数
     */
  onReachBottom: function() {}
})
